package receiver.screens;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.http.impl.client.DefaultHttpClient;
import edu.washington.cs.sounddetector.server.api.SoundDetectorAPI;
import edu.washington.cs.sounddetector.server.api.object.Notification;
import edu.washington.cs.sounddetector.server.api.object.PeakEvent;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ReceiverPhoneActivity extends Activity {
	private Button soundboardButton;
	private Button historyButton;
	private VisualizationView vis;
	private LinearLayout layout;
	private SoundDetectorAPI api;
	protected  String id;
	private Button repeat;
	private TextView location;
	private TextView guess;
	private String phoneName;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.main);
        //soundboardButton = (Button) findViewById(R.id.soundboard_button);
        //soundboardButton.setOnClickListener(new SoundboardButtonListener(this));
        historyButton = (Button) findViewById(R.id.history_button);
        historyButton.setOnClickListener(new HistoryButtonListener(this));
        repeat = (Button) findViewById(R.id.repeat_button);
        layout = (LinearLayout) findViewById(R.id.visualization_layout);
        location = (TextView) findViewById(R.id.main_location);
        guess = (TextView) findViewById(R.id.main_guess);
        
        Intent intent = getIntent();
        if(intent.getExtras() != null && intent.getExtras().getString("cloudID") != null) {
        	id = intent.getExtras().getString("cloudID");
        	phoneName = "Demo";
        	setupReceive();
        	getData();
        }else {
        	id = null;
        	phoneName = "test";
        	setupReceive();
        	getData();
        	startC2D();
        	//startActivity(new Intent(this, SetupScreenActivity.class));
        }

       
    }
    
    private void startC2D() {
    	//new C2DMReceiver(this);
    	Intent regIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
    	regIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0));
    	regIntent.putExtra("sender", "sounddetector@gmail.com");
    	startService(regIntent);
    }
    
    protected void setupReceive() {
    	try {
			api = new SoundDetectorAPI(new URI("http://kiska.cs.washington.edu:8080/sound-detector-test"), new DefaultHttpClient());
		} catch (URISyntaxException e) {
			// TODO ERROR RECOVERY
			Log.e("API", Log.getStackTraceString(e));
		}
		try {
			api.registerReceiverPhone(phoneName, id);
		} catch (Exception e) {
			Log.e("API", Log.getStackTraceString(e));
		}
    }
    
    protected void getData() {
		List<Notification> ln = null;
		try {
			if(phoneName.equals("test"))
				ln = api.getOldNotifications(phoneName, new Date(0), new Date());
			else
				ln = api.getPendingNotifications(phoneName);
			//ln = api.getPendingNotifications("test");
		} catch (Exception e) {
			// TODO ERROR RECOVERY
			Log.e("BOOM", Log.getStackTraceString(e));
		}
		if(ln == null || ln.isEmpty())
			return;
		visualize(ln.get(ln.size() - 1));
		
	}
    
    private void visualize(Notification n) {
    	List<VisualizationData> data = new ArrayList<VisualizationData>();
		for(PeakEvent peak : n.getPeakEvents()) {
			VisualizationData d1 = new VisualizationData();
			d1.duration = (long) (peak.getDuration() * 1000 / VisualizationView.tickRatio);
			d1.start = (long) peak.getTime() * 1000 / VisualizationView.tickRatio;
			d1.loudness = Math.min(30, (int) peak.getMagnitude());
			d1.color = Color.WHITE;//n.getSoundClass().getRgbColor();
			data.add(d1);
		}
        vis = new VisualizationView(this, data);
        repeat.setOnClickListener(new RepeatButtonListener(vis));
        layout.addView(vis, 0);
        guess.setText(n.getSoundClass().getSoundClass());
        location.setText(n.getDetectorId());
    }
}